package com.ergwang.utils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Creat by ergWang
 * Date: 2020/5/29
 * Time: 11:43
 */
public class HttpUtils {
    public static String getRequestBody(HttpServletRequest request) throws IOException {
        // 获取请求体，并转成字符串类型
        ServletInputStream inputStream = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,length);
        }
        // 得到了请求体后转换为Java对象
        return outputStream.toString("utf-8");
    }
}
